<?php


namespace App\Http\Controllers;


use App\Jobs\TraceJob;
use App\Jobs\TraceJob2;
use App\W7OpenTracing\Carrier;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use OpenTracing\Tracer;
use const OpenTracing\Formats\TEXT_MAP;
use const OpenTracing\Tags\SPAN_KIND;

class BookController extends Controller
{
    public function __construct()
    {
        /** @var Tracer $tracer */
        $tracer = app()->make(Tracer::class);
        $this->tracer = $tracer;
    }

    /**
     * @var Tracer
     */
    private $tracer;

    public function index(Request $request)
    {
        $scope = $this->tracer->startActiveSpan('index');
        $span = $scope->getSpan();
        usleep(10);
        $span->finish();

        return 'ok';
    }

    public function job()
    {
        $span = $this->tracer->startActiveSpan('job')->getSpan();
        $carrier = [];
        $this->tracer->inject($span->getContext(), TEXT_MAP, $carrier);
        Log::info('carrier', $carrier);
        dump('trace', $this->tracer);

        TraceJob::dispatch($carrier);

        $span->finish();

        return 'job';
    }

    public function job2()
    {
        $span = $this->tracer->startActiveSpan('job')->getSpan();
        sleep(1);
        TraceJob2::dispatch()->carrier(Carrier::fromSpan($span))->delay(3);

        $span->finish();

        return 'job';
    }

    public function tracer()
    {
        $span = $this->tracer->startActiveSpan('begin')->getSpan();
        $span->setTag(SPAN_KIND, 'server');
        $span->addBaggageItem('t', 't');

        $carrier = [];
        $this->tracer->inject($span->getContext(), TEXT_MAP, $carrier);

        $client = new Client();
        $resp = $client->get('http://127.0.0.1:8001/book/index', ['headers' => $carrier]);
        $result = $resp->getBody()->getContents();
        $span->finish();

        echo $result;
    }

    public function w7tracer()
    {
        $carrier = Carrier::fromRequest();
        dd($carrier);
    }
}
